package com.vehicle_information_management_system.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehicle_information_management_system.pojo.AdminInfo;
import com.vehicle_information_management_system.service.impl.AdminInfoServiceImpl;
import com.vehicle_information_management_system.utils.JwtUtil;
import com.vehicle_information_management_system.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminInfoController {
    @Autowired
    private AdminInfoServiceImpl adminInfoService;
    @RequestMapping("/login")
    public Result<?> login(@RequestParam String loginName, @RequestParam String password) {
        AdminInfo adminInfo=adminInfoService.login(loginName, password);
        log.info("adminInfo:{}",adminInfo);
        if (adminInfo == null) {
            return Result.error(400, "用户名或密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("adminId", adminInfo.getAdminId());
        map.put("loginName", adminInfo.getLoginName());
        map.put("role", adminInfo.getRole());
        String token = JwtUtil.generateToken(adminInfo.getLoginName(), adminInfo.getAdminId());
        map.put("token", token);
        return Result.success("登录成功",map);
    }
    @RequestMapping("/register")
    public Result<?> register(@RequestBody AdminInfo adminInfo) {
        try {
            adminInfoService.register(adminInfo);
        } catch (Exception e) {
            return Result.error(400, e.getMessage());
        }
        return Result.success("注册成功");
    }
    @RequestMapping("/update")
    public Result<?> update(@RequestBody AdminInfo adminInfo) {
        try {
            adminInfoService.update(adminInfo);
        } catch (Exception e) {
            return Result.error(400, e.getMessage());
        }
        return Result.success("修改成功");
    }
    @RequestMapping("/delete/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        try {
            adminInfoService.delete(id);
        } catch (Exception e) {
            return Result.error(400, e.getMessage());
        }
        return Result.success("删除成功");
    }
    @RequestMapping("/list")
    public Result<?> listPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        IPage<AdminInfo> page=adminInfoService.listPage(pageNum,pageSize,search);
        return Result.success(page);
    }
}
